package com.sbm.quartz;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import com.sbm.util.StringUtil;

@Component
@Configuration
public class QuartzJobScheduler {
    private static final Logger LOGGER = LoggerFactory.getLogger(QuartzJobScheduler.class);

    @Autowired
    private QuartzConfig config;

    @Autowired
    private QuartzJobFactory jobFactory;

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        LOGGER.info("————初始化Quartz————");
        LOGGER.info("Quartz：创建Factory[" + SchedulerFactoryBean.class.getName() + "]");
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setOverwriteExistingJobs(this.config.isOverwriteExistingJobs());
        factory.setAutoStartup(this.config.isAutoStartup());
        factory.setStartupDelay(this.config.getStartupDelay());
        if(!StringUtil.isEmpty(this.config.getProperties()))
        	factory.setQuartzProperties(quartzProperties());
        factory.setJobFactory(this.jobFactory);
        return factory;
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        String path = this.config.getProperties();
        LOGGER.info("Quartz：读取配置[" + path + "]");
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
        propertiesFactoryBean.setLocation(new ClassPathResource(path));
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }
}
